<!--
 * @author  dumeng
 新建/编辑新闻
-->
<template>
  <div class="news-create">
    <div class="news-create-title">新建/编辑新闻</div>
    <section v-loading="loading" class="news-create-main">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" class="form">
        <el-form-item label="新闻分类" prop="newsType">
          <el-select v-model="form.newsType" placeholder="请选择分类" clearable :style="{ width: '100%' }">
            <el-option v-for="(item, index) in classifyOptions" :key="index" :label="item.classifyName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="标题" prop="mainTitle">
          <el-input v-model="form.mainTitle" placeholder="请输入新闻标题" />
        </el-form-item>
        <el-form-item label="展示类型" prop="showType">
          <el-select v-model="form.showType" placeholder="请选择展示类型" clearable :style="{ width: '100%' }" @change="changeClearnD">
            <el-option v-for="(item, index) in dict.ZSXS" :key="index" :label="item.dictName" :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <!--<el-form-item label="副标题">
          <el-input v-model="form.withTitle" placeholder="请输入新闻副标题"/>
        </el-form-item>-->
        <el-form-item v-if="form.showType == 'ZSXS_ZWYTYS' || form.showType == 'ZSXS_YWZTYS'" label="引导图" prop="coverImgId" required>
          <image-upload
            :key="uploadFile.viewId"
            v-model="form.coverImgId"
            :preview-id="uploadFile.viewId"
            :forever="true"
            :width="654"
            :height="368"
            :view="uploadFile.view"
            :no-circle="true"
            :no-rotate="false"
            lang-type="zh"
            :is-oss="uploadFile.isOss"
            @changeOssPath="changeOssPath"
          />
        </el-form-item>
        <el-form-item v-if="form.showType == 'ZSXS_TWHPDTYS'" label="多图模式（小）封面" prop="smallCoverImgId" required>
          <image-upload-list
            :key="new Date().getTime()"
            v-model="form.smallCoverImgId"
            :multiple="true"
            :same-size-icon="true"
            :width="214"
            :height="148"
            :img-list="imgIdList"
            text-tips="上传"
            @changeImgV="changeImgV"
            @changeImgPush="changeImgPush"
          />
        </el-form-item>
        <el-form-item v-if="form.showType == 'ZSXS_TWHPBTYS'" label="大图模式封面" prop="bigCoverImgId" required>
          <image-upload-list
            :key="new Date().getTime()"
            v-model="form.bigCoverImgId"
            :multiple="true"
            :same-size-icon="true"
            :width="654"
            :height="368"
            :img-list="imgIdList1"
            text-tips="上传"
            @changeImgPush="changeImgPush"
          />
        </el-form-item>
        <el-form-item
          v-if="form.showType == 'ZSXS_YWYSYS' || form.showType == 'ZSXS_YWZSYS' || form.showType == 'ZSXS_TWHPDSYS'"
          label="视频模式"
          prop="videoId"
          required
        >
          <!-- :key="new Date().getTime()" -->
          <image-upload-list
            v-if="form.showType == 'ZSXS_TWHPDSYS'"
            :videos-list="imgIdList2"
            upload-type="videoImg"
            video-img-type="big"
            text-tips="上传视频封面（大）"
            :width="654"
            :height="368"
            :set-value="setVideoInfo"
            :set-img-value="setImgVB"
            :view-img="viewVideoImg"
            @changeImgPush="changeImgPush"
          />
          <!-- :key="new Date().getTime()" -->
          <image-upload-list
            v-if="form.showType == 'ZSXS_YWYSYS' || form.showType == 'ZSXS_YWZSYS'"
            :videos-list="imgIdList2"
            upload-type="videoImg"
            video-img-type="min"
            :width="228"
            :height="148"
            text-tips="上传视频封面（小）"
            :set-value="setVideoInfo"
            :set-img-value="setImgVS"
            :view-img="viewVideoImg"
            @changeImgPush="changeImgPush"
          />
        </el-form-item>

        <el-form-item
          v-if="form.showType === 'ZSXS_YWYSYS' || form.showType === 'ZSXS_YWZSYS' || form.showType === 'ZSXS_TWHPDSYS'"
          label="视频时长（秒）"
          prop="param3"
        >
          <el-input v-model="form.param3" placeholder="请输入视频时长（秒）" />
        </el-form-item>
        <el-form-item label="发布人" prop="publisher">
          <el-input v-model="form.publisher" placeholder="请输入发布人" />
        </el-form-item>
        <el-form-item label="发布时间" prop="publishTime">
          <el-date-picker
            v-model="form.publishTime"
            type="date"
            placeholder="选择发布时间"
            style="width: 100%"
            format="yyyy-MM-dd"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="来源" prop="source">
          <el-input v-model="form.source" placeholder="请输入新闻来源" />
        </el-form-item>
        <el-form-item label="简介">
          <el-input v-model="form.briefIntroduction" :rows="6" type="textarea" placeholder="请输入新闻简介" />
        </el-form-item>
        <el-form-item label="正文">
          <tinymce v-if="showtinymce" v-model="form.text" :is-oss="uploadFile.isOss" :height="300" />
        </el-form-item>
        <!--<el-form-item label="新闻图片">
          <div class="selectbtn" @click="imagesAdd">添加图片</div>
          <el-card class="news-image" v-if="imagesList.length">
            <el-row :gutter="10">
              <draggable v-model="imagesList" :animation="340"
                         handle=".image-index-move" filter=".no-drag-item" draggable=".drag-item">
                <el-col :span="8"
                        v-for="(item, index) in imagesList"
                        class="images-item"
                        :class="{'no-drag-item': !item || !item.attachmentId, 'drag-item': item && item.attachmentId}"
                >
                  <div class="custom-uploader">
                    <img class="upload-img" :src="uploadFile.view + item.attachmentId">
                    <el-button @click="imagesDel(item, index)" style="padding: 3px 0; font-size: 20px;" type="text"
                               icon="el-icon-close"></el-button>
                    <el-tooltip class="item" effect="dark" content="拖动调整顺序" placement="top">
                      <el-button class="image-index-move" style="padding: 3px 0; font-size: 20px;" type="text"
                                 icon="el-icon-rank"></el-button>
                    </el-tooltip>
                  </div>
                  <el-input
                    v-model="item.explain"
                    placeholder="请输入内容"
                    maxlength="100"
                    style="width: 100%"
                  />
                </el-col>
              </draggable>
            </el-row>
          </el-card>
        </el-form-item>
        <el-form-item label="新闻视频">
          <div class="selectbtn" @click="videosAdd">添加视频</div>
          <el-card v-if="videosList.length">
            <el-row class="attachment-item" :gutter="10">
              <draggable v-model="videosList" :animation="340" handle=".video-index-move">
                <el-col :span="8" class="video-item" v-for="(item, index) in videosList"
                        v-if="item &&  item.attachmentId">
                  <img class="upload-img" @click="handlePreview(item.attachmentId, index)"
                       v-if="item && item.attachmentId" src="../images/video-poster.png">
                  <el-button @click="videosDel(item, index)" style="padding: 3px 0; font-size: 20px;" type="text"
                             icon="el-icon-close"></el-button>
                  <el-tooltip class="item" effect="dark" content="拖动调整顺序" placement="top">
                    <el-button class="video-index-move" style="padding: 3px 0; font-size: 20px;" type="text"
                               icon="el-icon-rank"></el-button>
                  </el-tooltip>
                </el-col>
              </draggable>
            </el-row>
          </el-card>
        </el-form-item>-->

        <el-form-item label="新闻音频" prop="audioId">
          <div v-if="!form.audioId.id" class="selectbtn" @click="uploadFileAdiuo.showUpload = true">开始上传</div>
          <template v-else>
            <div :key="form.audioId" class="select-data">
              {{ uploadFileAdiuo.file.name }}
              <i class="el-icon-close" @click="clearAdiuoFile" />
            </div>
            <div>
              <video
                v-if="form.audioId.id !== ''"
                class="video"
                style="height: 36px;width: 380px"
                controls
                :src="uploadFile.view + form.audioId.id"
              />
            </div>
            <!-- <i class="el-icon-view" @click="previewAdiuoFile"></i> -->
          </template>
          <Upload
            v-if="uploadFileAdiuo.showUpload"
            ref="upload"
            :accept="uploadFileAdiuo.accept"
            :limit="1"
            :show-chunks="true"
            :multiple="false"
            :is-oss="isOss"
            :chunk-size="uploadFileAdiuo.chunksize"
            @close="uploadFileAdiuo.showUpload = false"
            @success="uploadAdiuoSuccess"
          >
            <div slot="tip" class="upload-tip">
              <i class="el-icon-info" />
              : 只能上传：音频
            </div>
          </Upload>
        </el-form-item>
        <el-form-item label="附件">
          <div class="selectbtn" @click="filesAdd">添加附件</div>
          <draggable v-if="filesList.length" v-model="filesList" :animation="340" handle=".file-index-move">
            <el-row v-for="(item, index) in filesList" :key="index" class="attachment-item">
              <section v-if="item.attachmentId">
                <el-col :span="8">
                  <el-input v-model="item.attachmentName" @blur="isEmpty" />
                </el-col>
                <el-col :span="1" style="text-align: center">
                  <el-button style="padding: 3px 0; font-size: 22px" type="text" icon="el-icon-close" @click="filesDel(item, index)" />
                </el-col>
                <el-col :span="1" style="text-align: center">
                  <el-tooltip class="item" effect="dark" content="拖动调整顺序" placement="top">
                    <el-button class="file-index-move" style="padding: 3px 0; font-size: 22px" type="text" icon="el-icon-rank" />
                  </el-tooltip>
                </el-col>
              </section>
            </el-row>
          </draggable>
        </el-form-item>
        <!--<el-form-item label="责任编辑" prop="param1">
          <el-input v-model="form.param1" placeholder="请输入责任编辑"/>
        </el-form-item>-->
        <!-- <el-form-item label="是否必修">
          <el-radio-group v-model="definition">
            <el-radio label="1">必修</el-radio>
            <el-radio label="2">选修</el-radio>
          </el-radio-group>
        </el-form-item> -->
        <!-- <el-form-item label="可获得学时" prop="getReward">
          <el-input v-model="getReward" placeholder="请输入可获得学时" />
        </el-form-item> -->
        <el-form-item label="排序" prop="sort">
          <el-input v-model.number="form.sort" placeholder="请输入排序号（值越大，越靠前）" />
        </el-form-item>
        <!--<el-form-item label="业务字段2" prop="param2">
          <el-input v-model="form.param2" placeholder="请输入业务字段2"/>
        </el-form-item>
        <el-form-item label="业务字段3" prop="param3">
          <el-input v-model="form.param3" placeholder="请输入业务字段3"/>
        </el-form-item>
        <el-form-item label="业务字段4" prop="param4">
          <el-date-picker v-model="form.param4" type="datetime" placeholder="选择业务字段4" style="width: 100%;"
                          format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"/>
        </el-form-item>
        <el-form-item label="业务字段5" prop="param5">
          <el-date-picker v-model="form.param5" type="datetime" placeholder="选择业务字段5" style="width: 100%;"
                          format="yyyy-MM-dd HH:mm:ss" value-format="yyyy-MM-dd HH:mm:ss"/>
        </el-form-item>
        <el-form-item label="业务字段6" prop="param6">
          <el-input-number v-model="form.param6" :min="1"></el-input-number>
        </el-form-item>-->
      </el-form>
    </section>
    <section class="news-create-footer">
      <el-button style="padding: 10px 30px" @click="handleCancel">取 消</el-button>
      <el-button type="primary" @click="onSubmint('form')">确 定</el-button>
    </section>
    <video-upload
      v-if="uploadFile.showUpload === 1"
      ref="videoUpload"
      :accept="uploadFile.accept"
      :limit="1"
      :show-chunks="true"
      :multiple="false"
      :chunk-size="uploadFile.chunksize"
      @close="uploadFile.showUpload = -1"
      @success="uploadSuccess"
    >
      <div slot="tip" class="upload-tip">
        <i class="el-icon-info" />
        :
        {{ uploadFile.fileType | filterTip }}
      </div>
    </video-upload>
    <image-no-cropper-upload
      v-if="uploadFile.showUpload === 2"
      ref="imageUpload"
      :accept="uploadFile.accept"
      :limit="1"
      :show-chunks="true"
      :multiple="false"
      :chunk-size="uploadFile.chunksize"
      @close="uploadFile.showUpload = -1"
      @success="uploadSuccess"
    >
      <div slot="tip" class="upload-tip">
        <i class="el-icon-info" />
        :
        {{ uploadFile.fileType | filterTip }}
      </div>
    </image-no-cropper-upload>
    <upload
      v-if="uploadFile.showUpload === 3"
      ref="upload"
      :accept="uploadFile.accept"
      :limit="1"
      :show-chunks="true"
      :multiple="false"
      :chunk-size="uploadFile.chunksize"
      @close="uploadFile.showUpload = -1"
      @success="uploadSuccess"
    >
      <div slot="tip" class="upload-tip">
        <i class="el-icon-info" />
        :
        {{ uploadFile.fileType | filterTip }}
      </div>
    </upload>
    <el-dialog v-el-drag-dialog :close-on-click-modal="false" :visible.sync="preview.state" title="预览" center width="600px">
      <preview :file-id="preview.fileId" />
    </el-dialog>
    <el-dialog v-el-drag-dialog :close-on-click-modal="false" :visible.sync="imageaddState" title="图片上传" center width="600px">
      <div class="image-upload-dialog">
        <el-form label-width="80px">
          <el-form-item label="图片">
            <img v-if="imageadd.attachmentId" class="upload-img" :src="uploadFile.view + imageadd.attachmentId">
            <div v-else class="icon-wrap" @click="handleFileUpload('image')">
              <i class="el-icon-plus avatar-uploader-icon" />
            </div>
          </el-form-item>
          <el-form-item label="简介">
            <el-input v-model="imageadd.explain" placeholder="请输入内容" maxlength="100" style="width: 100%" />
          </el-form-item>
        </el-form>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button style="padding: 8px 30px" type="primary" @click="handleCancel">取消</el-button>
        <el-button style="padding: 8px 30px" type="primary" @click="submitUploadImage()">确认</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import ImageUpload from '@/components/ImageUpload'
import Upload from '@/components/upload'
import Preview from '../components/VideoPreview'
import draggable from 'vuedraggable'
import { getClassifyTree, insert, update, get } from '../api'
import Tinymce from '@/components/Tinymce'
import elDragDialog from '@/directive/el-drag-dialog'
import VideoUpload from '@/components/VideoUpload'
import ImageNoCropperUpload from '@/components/ImageNoCropperUpload' // base on element-ui
import ImageUploadList from '../components/ImageUploadList'
import { getDictByCode } from '../api'

export default {
  name: 'NewsManage',
  components: {
    ImageUpload,
    VideoUpload,
    Upload,
    ImageNoCropperUpload,
    Tinymce,
    Preview,
    draggable,
    ImageUploadList
  },
  directives: { elDragDialog },
  filters: {
    filterTip(ft) {
      if (ft === 'image') {
        return '只能上传：图片文件'
      } else if (ft === 'video') {
        return '只能上传：视频文件'
      } else {
        return '请上传附件'
      }
    }
  },
  data() {
    return {
      isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false,
      uploadFileAdiuo: {
        showUpload: false,
        accept: 'audio/*',
        chunksize: 10 * 1024 * 1024,
        file: '',
        oldfile: ''
      },
      loading: false,
      showtinymce: false,
      getReward: '0',
      definition: '2',
      form: {
        audioId: {
          id: '',
          name: '',
          subjectDuration: '',
          ossPath: ''
        }, // 班级视频
        id: '',
        newsType: '',
        mainTitle: '',
        withTitle: '',
        briefIntroduction: '',
        coverImgId: '',
        source: '',
        text: '',
        sort: '',
        publisher: '',
        publishTime: '',
        param1: '',
        param2: '',
        param3: '',
        param4: '',
        param5: '',
        param6: '',
        showType: '',
        smallCoverImgId: '',
        bigCoverImgId: '',
        videoId: '',
        videoSmallCoverImgId: '',
        videoBigCoverImgId: ''
      },
      rules: {
        newsType: [{ required: true, message: '请选择新闻分类', trigger: 'change' }],
        mainTitle: [
          { required: true, message: '请输入新闻标题', trigger: 'blur' },
          {
            min: 1,
            max: 200,
            message: '长度在 1 到 200 个字符',
            trigger: 'blur'
          }
        ],
        coverImgId: [{ required: true, message: '请上传引导图', trigger: 'change' }],
        showType: [{ required: true, message: '请选择展示类型', trigger: 'change' }]
      },
      imagesList: [],
      videosList: [],
      filesList: [],
      imageaddState: false,
      imageadd: {
        attachmentId: '',
        explain: '',
        attachmentName: ''
      },
      state: 'create',
      classifyOptions: [],
      uploadFile: {
        viewId: '',
        view: '/API-DOCUMENT/document/file/download?id=',
        imagecropperKey: 0,
        showUpload: -1, // 1视频 2图片 3附件
        accept: '',
        fileType: '',
        fileIndex: 0,
        isOss: sessionStorage.getItem('FILE_SAVE_THIRD_CONFIG') || false
      },
      preview: {
        state: false,
        fileId: ''
      },
      showTypeOptions: [
        { id: 1, name: '左文右图样式' },
        { id: 2, name: '左文右视样式' },
        { id: 3, name: '右文左图样式' },
        { id: 4, name: '右文左视样式' },
        { id: 5, name: '图文混排-多图样式' },
        { id: 6, name: '图文混排-大图样式' },
        { id: 7, name: '图文混排-大视样式' },
        { id: 8, name: '纯文字' }
      ],
      imgIdList: [],
      imgIdList1: [],
      imgIdList2: [],
      dict: {
        ZSXS: [] // 报名审核状态
      },
      viewVideoImg: ''
    }
  },
  async created() {
    this.state = this.$route.query.type === 'u' ? 'update' : 'create'
    this.getClassifyOption().then(() => {
      // this.form.newsType = this.$route.query.c || ''
    })
    if (this.$route.query.type === 'u') {
      if (!this.$route.query.i) {
        this.$message({
          showClose: true,
          message: '参数异常！',
          type: 'warning',
          onClose: () => {
            this.handleCancel()
          }
        })
      }
    } else {
      this.showtinymce = true
      this.form.publishTime = this.dateFormat('yyyy-MM-dd', new Date())
    }
    for (const key in this.dict) {
      await this.getDict(key)
    }
  },
  methods: {
    changeImgV(ids) {
      const idsList = ids.split(',')
      const dataClone = JSON.parse(JSON.stringify(this.imgIdList))
      this.imgIdList = []
      dataClone.forEach((item) => {
        if (idsList.includes(item.id)) {
          this.imgIdList.push({ url: this.uploadFile.view + item.id, id: item.id })
        }
      })
    },
    changeImgPush(path) {
      this.showtinymce = false
      this.$nextTick(() => {
        this.form.text = this.form.text + `<p><img class='wscnph' src='${path}' width='100%' /></p>`
        this.showtinymce = true
      })
    },
    changeOssPath(path) {
      this.uploadFile.viewId = path
      this.showtinymce = false
      this.$nextTick(() => {
        this.form.text = this.form.text + `<p><img class='wscnph' src='${path}' width='100%' /></p>`
        this.showtinymce = true
      })
    },
    // 视频上传完成回调
    uploadAdiuoSuccess(id, files, ossPath) {
      console.log(ossPath, files[0], id)
      if (id) {
        this.$set(this.form, 'audioId', {
          id: id,
          name: files[0].name.substring(0, files[0].name.lastIndexOf('.')),
          subjectDuration: files[0].duration,
          ossPath: ossPath
        })
        // this.form.videoId.id = id
        // this.form.videoId.name = files[0].name.substring(0, files[0].name.lastIndexOf('.'))
        // this.form.videoId.subjectDuration = files[0].duration
        this.uploadFileAdiuo.file = files[0]
        this.uploadFileAdiuo.showUpload = false
      }
    },
    // 清除文件
    clearAdiuoFile() {
      this.uploadFileAdiuo.file = ''
      this.form.audioId.id = ''
      this.form.audioId.name = ''
      this.form.audioId.subjectDuration = ''
      this.form.audioId.ossPath = ''
    },
    /**
     * 字典
     */
    getDict(code) {
      return new Promise((resolve, reject) => {
        getDictByCode(code)
          .then((response) => {
            this.dict[code] = response.data.data[0].list
            resolve()
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /**
     * 返回
     */
    handleCancel() {
      this.$router.replace({
        path: this.$filterPath('zoneResources'),
        query: { c: this.$route.query.c, id: this.$route.query.id, name: this.$route.query.name }
      })
    },
    CleanPastedHTML(input) {
      if (!input) {
        return ''
      }
      input = input.replace(/<\/?[^>]*>/g, '') // 去除HTML tag
      input = input.replace(/(\r)/gi, '')
      input = input.replace(/(\n)/gi, '')
      input = input.replace(/(\t)/gi, '')
      input = input.replace(/ /gi, '') // 去掉
      return input.replace(/&(.*?);/gi, '')
    },
    /**
     * 获取分类
     */
    getClassifyOption() {
      return new Promise((resolve, reject) => {
        getClassifyTree({ classifyType: 'XWFL_XWGL' })
          .then(({ data }) => {
            this.classifyOptions = data.data || []
            resolve()
            if (this.state === 'update') {
              this.getData(this.$route.query.i)
            } else {
              this.form.newsType = this.classifyOptions[0]?.id
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    isEmpty(e) {
      if (e.target.value === '') {
        this.$message({
          message: '附件名称不能为空！',
          type: 'warning'
        })
      }
    },
    handleFileUpload(fileType, i) {
      this.uploadFile.fileType = fileType
      this.uploadFile.fileIndex = i
      if (fileType === 'video') {
        this.uploadFile.accept = 'video/mp4'
        this.uploadFile.showUpload = 1
      } else if (fileType === 'image') {
        this.uploadFile.accept = 'image/*'
        this.uploadFile.showUpload = 2
      } else {
        this.uploadFile.accept = ''
        this.uploadFile.showUpload = 3
      }
    },
    /**
     * 新闻图片-继续添加
     */
    imagesAdd() {
      for (const i in this.imageadd) {
        this.imageadd[i] = ''
      }
      this.imageaddState = true
    },
    submitUploadImage() {
      const obj = Object.assign({}, this.imageadd)
      this.imagesList.push(obj)
      this.imageaddState = false
    },
    /**
     * 新闻视频-继续添加
     */
    videosAdd() {
      if (this.videosList.length === 0 || this.videosList[this.videosList.length - 1].attachmentId !== '') {
        const temp = {
          attachmentId: '',
          explain: '',
          attachmentName: ''
        }
        this.videosList.push(temp)
      }
      this.handleFileUpload('video', this.videosList.length - 1)
    },
    /**
     * 新闻附件-继续添加
     */
    filesAdd() {
      const temp = {
        attachmentId: '',
        explain: '',
        attachmentName: '',
        attachmentNameOld: ''
      }
      this.filesList.push(temp)
      this.handleFileUpload('file', this.filesList.length - 1)
    },
    /**
     * 新闻图片-删除
     */
    imagesDel(item, index) {
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.imagesList.splice(index, 1)
        })
        .catch()
    },
    /**
     * 新闻视频-删除
     */
    videosDel(item, index) {
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.videosList.splice(index, 1)
        })
        .catch()
    },
    /**
     * 新闻附件-删除
     */
    filesDel(item, index) {
      this.$confirm('确定删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.filesList.splice(index, 1)
        })
        .catch()
    },
    uploadSuccess(id, files) {
      if (id) {
        const fileType = this.uploadFile.fileType
        const fileIndex = this.uploadFile.fileIndex
        if (fileType === 'image') {
          this.imageadd.attachmentId = id
          this.imageadd.attachmentName = files[0].name
        } else if (fileType === 'video') {
          this.videosList[fileIndex].attachmentId = id
          this.videosList[fileIndex].attachmentName = files[0].name
        } else {
          this.filesList[fileIndex].attachmentId = id
          this.filesList[fileIndex].attachmentName = files[0].name
          this.filesList[fileIndex].attachmentNameOld = files[0].name
        }
      }
      this.uploadFile.showUpload = -1
    },
    /**
     * 视频预览
     */
    handlePreview(id) {
      this.preview.fileId = id
      this.preview.state = true
    },
    /**
     * 类型变化修改数据
     */
    changeClearnD() {
      this.imgIdList = []
      this.imgIdList1 = []
      this.imgIdList2 = []
      // this.form.coverImgId = ''
      this.form.smallCoverImgId = ''
      this.form.bigCoverImgId = ''
      this.form.videoId = ''
      this.form.videoSmallCoverImgId = ''
      this.form.videoBigCoverImgId = ''
    },
    /**
     * 上传视频回调赋值
     */
    setVideoInfo(id, time) {
      this.form.videoId = id
      this.form.param3 = time
    },
    setImgVB(id) {
      this.form.videoBigCoverImgId = id
    },
    setImgVS(id) {
      this.form.videoSmallCoverImgId = id
    },
    onSubmint() {
      if (
        this.filesList
          .filter((item) => {
            return item.attachmentId
          })
          .filter((ite) => {
            return ite.attachmentName === ''
          }).length > 0
      ) {
        this.$message({
          message: '请填写新闻附件名称！',
          type: 'warning'
        })
        return
      }
      if (this.state === 'create') {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })
            const params = Object.assign({}, this.form, {
              audioId: this.form.audioId ? this.form.audioId.id : ''
            })
            if (this.form.briefIntroduction === '') {
              const text = this.CleanPastedHTML(this.form.text)
              params['briefIntroduction'] = text.length > 200 ? text.substring(0, 200) : text.substring(0, text.length - 1)
            }
            params['picJson'] =
              this.imagesList.filter((item) => {
                return item.attachmentId
              }).length > 0
                ? JSON.stringify(
                  this.imagesList.filter((item) => {
                    return item.attachmentId
                  })
                )
                : ''
            params['videoJson'] =
              this.videosList.filter((item) => {
                return item.attachmentId && item.attachmentName
              }).length > 0
                ? JSON.stringify(
                  this.videosList.filter((item) => {
                    return item.attachmentId && item.attachmentName
                  })
                )
                : ''
            params['fileJson'] =
              this.filesList.filter((item) => {
                return item.attachmentId
              }).length > 0
                ? JSON.stringify(
                  this.filesList.filter((item) => {
                    return item.attachmentId
                  })
                )
                : ''
            const datas = {
              areaId: this.$route.query.id,
              type: this.$route.query.c,
              source: 2,
              resources: JSON.stringify(params),
              definition: this.definition,
              getReward: this.getReward,
              sort: params.sort
            }
            return new Promise((resolve, reject) => {
              insert(datas)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '创建成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.handleCancel()
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            console.log('error submit!!')
            return false
          }
        })
      } else {
        this.$refs['form'].validate((valid) => {
          if (valid) {
            const loading = this.$loading({
              lock: true,
              text: '请稍后',
              spinner: 'el-icon-loading',
              background: 'rgba(0, 0, 0, 0.3)'
            })

            const params = Object.assign({}, this.form, {
              audioId: this.form.audioId ? this.form.audioId.id : ''
            })
            if (this.form.briefIntroduction === '') {
              const text = this.CleanPastedHTML(this.form.text)
              params['briefIntroduction'] = text.length > 200 ? text.substring(0, 200) : text.substring(0, text.length - 1)
            }
            params['picJson'] =
              this.imagesList.filter((item) => {
                return item.attachmentId
              }).length > 0
                ? JSON.stringify(
                  this.imagesList.filter((item) => {
                    return item.attachmentId
                  })
                )
                : ''
            params['videoJson'] =
              this.videosList.filter((item) => {
                return item.attachmentId && item.attachmentName
              }).length > 0
                ? JSON.stringify(
                  this.videosList.filter((item) => {
                    return item.attachmentId && item.attachmentName
                  })
                )
                : ''
            params['fileJson'] =
              this.filesList.filter((item) => {
                return item.attachmentId
              }).length > 0
                ? JSON.stringify(
                  this.filesList.filter((item) => {
                    return item.attachmentId
                  })
                )
                : ''
            const datas = {
              id: this.form.id,
              areaId: this.$route.query.id,
              type: this.$route.query.c,
              source: 2,
              resources: JSON.stringify(params),
              definition: this.definition,
              getReward: this.getReward,
              sort: params.sort
            }
            return new Promise((resolve, reject) => {
              update(datas)
                .then(() => {
                  this.dialogVisible = false
                  loading.close()
                  this.$message({
                    title: '成功',
                    message: '修改成功',
                    type: 'success',
                    duration: 2000
                  })
                  this.handleCancel()
                })
                .catch((error) => {
                  reject(error)
                  loading.close()
                })
            })
          } else {
            return false
          }
        })
      }
    },
    /**
     * 根编辑回显
     */
    getData(id) {
      const loading = this.$loading({
        lock: true,
        text: '请稍后',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.3)'
      })
      return new Promise((resolve, reject) => {
        get({ id: id })
          .then((res) => {
            loading.close()
            const data = JSON.parse(res.data.data.resources)
            // this.form = data
            this.getReward = res.data.data.getReward
            this.definition = res.data.data.definition
            // this.uploadFile.viewId = data.imgUrl
            // const data = res.data.data
            for (const key in this.form) {
              if (key === 'audioId') {
                this.$set(this.uploadFileAdiuo, 'file', { name: data.audioId })
                this.$set(this.form, 'audioId', {
                  id: data.audioId,
                  ossPath: data.audioId,
                  name: data.audioId
                })
              } else {
                this.form[key] = data[key]
              }
            }
            this.form.id = res.data.data.id
            this.uploadFile.viewId = data.coverImgIdUrl || this.uploadFile.view + data.coverImgId
            this.imagesList = data.picList || []
            this.videosList = data.videoList || []
            this.filesList = data.fileList || []
            this.showtinymce = true
            // this.imgList.push({ url: this.uploadFile.view + id ,id:id})

            // this.imgIdList: [],
            // this.imgIdList1: [],
            // this.imgList.push({ url: this.uploadFile.view + id ,id:id})
            // 多小图
            if (data.showType == 'ZSXS_TWHPDTYS') {
              const arrS = data.smallCoverImgId.split(',') || []
              this.imgIdList = []
              arrS.forEach((item) => this.imgIdList.push({ url: this.uploadFile.view + item, id: item }))
            }
            // 多大图
            if (data.showType == 'ZSXS_TWHPBTYS') {
              const arrS = data.bigCoverImgId.split(',') || []
              this.imgIdList1 = []
              arrS.forEach((item) => this.imgIdList1.push({ url: this.uploadFile.view + item, id: item }))
            }
            // 视频与图
            if (data.showType == 'ZSXS_YWYSYS' || data.showType == 'ZSXS_YWZSYS' || data.showType == 'ZSXS_TWHPDSYS') {
              const temp = {
                attachmentId: data.videoId,
                explain: '',
                attachmentName: ''
              }
              this.imgIdList2.push(temp)
            }
            if (data.showType == 'ZSXS_YWYSYS' || data.showType == 'ZSXS_YWZSYS') {
              this.viewVideoImg = data.videoSmallCoverImgIdUrl || this.uploadFile.view + data.videoSmallCoverImgId
            } else {
              this.viewVideoImg = data.videoBigCoverImgIdUrl || this.uploadFile.view + data.videoBigCoverImgId
            }
            this.$forceUpdate()
          })
          .catch((error) => {
            loading.close()
            reject(error)
          })
      })
    },
    dateFormat(fmt, date) {
      let ret
      const opt = {
        'y+': date.getFullYear().toString(), // 年
        'M+': (date.getMonth() + 1).toString(), // 月
        'd+': date.getDate().toString(), // 日
        'H+': date.getHours().toString(), // 时
        'm+': date.getMinutes().toString(), // 分
        's+': date.getSeconds().toString() // 秒
        // 有其他格式化字符需求可以继续添加，必须转化成字符串
      }
      for (const k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt)
        if (ret) {
          fmt = fmt.replace(ret[1], ret[1].length === 1 ? opt[k] : opt[k].padStart(ret[1].length, '0'))
        }
      }
      return fmt
    }
  }
}
</script>

<style rel="stylesheet/scss" lang="scss">
.news-create {
  background-color: #fff;
  min-height: calc(100vh - 60px);
  max-height: calc(100vh - 60px);
  overflow: hidden;

  .news-create-title {
    position: relative;
    height: 40px;
    line-height: 40px;
    padding: 0 20px;
    background-color: #ffffff;
    border-bottom: 1px solid #e5e5e5;
    font-family: PingFangSC-Medium;
    font-weight: bold;
    color: rgba(51, 51, 51, 1);
    font-size: 14px;

    &:before {
      content: '';
      position: absolute;
      width: 2px;
      @include bg-color($mainColor);
      top: 13px;
      bottom: 13px;
      left: 15px;
    }
  }

  .news-create-main {
    position: absolute;
    top: 50px;
    left: 0;
    right: 0;
    bottom: 52px;
    box-sizing: border-box;
    padding: 0 10px;
    overflow: hidden;

    &::-webkit-scrollbar {
      width: 8px; /*对垂直流动条有效*/
      height: 1px; /*对水平流动条有效*/
    }

    /** 滚动条轨道*/
    &::-webkit-scrollbar-track {
      box-shadow: inset 0 0 6px rgba(0, 0, 0, 0.1);
      background-color: white;
      border-radius: 3px;
    }

    /** 滚动条里面小方块*/
    &::-webkit-scrollbar-thumb {
      height: 32px;
      border-radius: 5px;
      box-shadow: inset 0 0 4px rgba(0, 0, 0, 0.1);
      background-color: #eaeaea;
    }

    &:hover {
      overflow: auto;
    }

    .form {
      width: 1000px !important;
      margin: 0 auto;

      .el-select {
        width: 100%;
      }

      .line {
        text-align: center;
      }
    }

    .select-data {
      display: inline-block;
      background: rgba(246, 246, 246, 1);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      color: rgba(51, 51, 51, 1);
      padding: 0 10px;
      margin-right: 5px;
      margin-bottom: 8px;

      i {
        cursor: pointer;
        padding-left: 5px;
      }
    }

    .selectbtn {
      display: inline-block;
      width: 120px;
      background: rgba(255, 255, 255, 1);
      @include border-color(1px, dotted, $mainColor);
      border-radius: 4px;
      font-size: 14px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      @include font-color($mainColor);
      text-align: center;
      cursor: pointer;
      margin-bottom: 10px;
    }

    .news-image {
      .el-card__header {
        padding-top: 8px;
        padding-bottom: 8px;
      }
    }

    .images-item {
      position: relative;
      margin-bottom: 10px;

      .upload-img {
        width: 100%;
        height: 160px;
        display: block;
      }

      .el-input {
        display: block;
      }

      .custom-uploader {
        width: 100%;
        display: block;

        .icon-wrap {
          width: 100%;
          height: 160px;
        }
      }

      .el-button {
        position: absolute;
        right: 10px;
        top: 0;
        color: #fff;

        i {
          background: rgba(0, 0, 0, 0.4);
          border-radius: 50%;
          padding: 2px;
        }

        &.image-index-move {
          right: 40px;
        }
      }
    }

    .images-add {
      color: $mainColor;
      font-size: 14px;
      padding-left: 80px;
      cursor: pointer;
      margin-bottom: 20px;
    }

    .upload-img {
      width: 100%;
      height: 160px;
    }

    .attachment-item {
      margin-bottom: 10px;

      .item-btn {
        font-size: 20px;
        cursor: pointer;
      }

      .video-item {
        position: relative;
        cursor: pointer;

        .el-button {
          position: absolute;
          right: 10px;
          top: 0;
          color: #fff;

          i {
            background: rgba(0, 0, 0, 0.4);
            border-radius: 50%;
            padding: 2px;
          }

          &.video-index-move {
            right: 40px;
          }
        }
      }
    }
  }

  .news-create-footer {
    position: absolute;
    left: 0;
    right: 0;
    bottom: 0;
    text-align: center;
    padding: 10px 0;
    background-color: white;
    box-shadow: 0 -3px 6px #f5f5f5;
  }

  .image-upload-dialog {
    .icon-wrap {
      width: 300px;
      height: 160px;
      margin: 0 auto;
      display: flex;
      align-items: center;
      justify-content: center;
      background: rgba(247, 247, 248, 1);
      border: 1px solid rgba(226, 227, 232, 1);
      border-radius: 4px;

      .avatar-uploader-icon {
        font-size: 48px;
        color: #dadada;
        width: 300px;
        text-align: center;
      }
    }

    .upload-img {
      display: block;
      width: 300px;
      height: 160px;
      border-radius: 4px;
    }
  }
}
</style>
